<script>
import MAIN_STORE from "@/store/store.js";
import { CloseBold, Location, Download, Switch, Sort } from "@element-plus/icons-vue";
import { ElMessage } from 'element-plus'
import { MeasureDuanmianVer, MeasureDuanmianHor } from "@/utils/Measure";
import mitt from "mitt";
import { ref, reactive } from "vue";
import SelfDraggable from '@/components/Draggable/Draggable.vue';
import Api from '@/Api'
let mittBus = null;
function getListData(data) {
  const filtersAttr = ['pointion']
  const keys = Object.keys(data || {}).filter(v => {
    return filtersAttr.indexOf(v) === -1;
  })
  const listData = keys.map(v => { return { key: v, value: data[v] } })
  return listData
}
export default {
  /**
   * 净距分析
   */
  name: "decision-duanmian",
  components: { CloseBold, Location, SelfDraggable, Download, Switch, Sort },
  data() {
    return {
      dialogDrawer: false,
      // 表单
      realForm: {
        radius: 50,
        type: 'point'
      },
      // 是否正在绘制
      isPainting: false,
      // 是否有查询的数据
      dataForPaintVER: [],
      dataForPaintHOR: [],
      bufferForm: {
        "drawPoints": {
          "coordinates": [],
          "crs": { "type": "MultiLineString", "properties": { "name": "EPSG:4326" } }
        }
      },
      // 选中的项 id
      selectedId: null,
      listData: [],
      emptyText: '暂无数据',
      colorOfLine: 'rgba(19, 206, 102, 0.8)',
      mainTitle: '断面分析',
      currentType: '',
      imageSrc: ''
    };
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    }
  },
  computed: {
    mainTitle_() {
      if (!this.currentType) { return '' }
      return {
        VER: '[纵断面分析]',
        HOR: '[横断面分析]'
      }[this.currentType]
    }
  },
  watch: {
    visible: function (nV) {
      if (!nV) {
        const insVer = MeasureDuanmianVer.getIns();
        insVer && insVer.destroy();
        const insHor = MeasureDuanmianHor.getIns();
        insHor && insHor.destroy();
        this.dataForPaintVER = [];
        this.dataForPaintHOR = [];
        this.selectedId = null;
      }
    }
  },
  mounted() {
  },
  beforeUnmount() {
    mittBus && mittBus.all.clear();
    mittBus = null;
    const insVer = MeasureDuanmianVer.getIns();
    insVer && insVer.destroy();
    const insHor = MeasureDuanmianHor.getIns();
    insHor && insHor.destroy();
    this.dataForPaintVER = [];
    this.dataForPaintHOR = [];
    this.selectedId = null;
  },
  methods: {
    // 开始选中点
    selectPoint(type) {
      this.dataForPaintVER = [];
      this.dataForPaintHOR = [];
      // this.bufferForm.polygon = null;
      // 如果正在绘制
      this.currentType = type;
      if (this.isPainting) {
        // 结束绘制
        this.isPainting = false;
        // 销毁绘制实例
        const insVer = MeasureDuanmianVer.getIns();
        insVer && insVer.destroy();

        const insHor = MeasureDuanmianHor.getIns();
        insHor && insHor.destroy();
        this.imageSrc = '';
      } else {
        // 开始绘制
        this.isPainting = true;
        // 生成绘制实例
        if (type === 'VER') {
          let insVer = MeasureDuanmianVer.getIns();
          if (!insVer) {
            mittBus = mitt();
            insVer = MeasureDuanmianVer.create({
              map: MAIN_STORE.GLOBAL_MAP_INS,
              overlayLimit: 5,
              mittBus: mittBus,
              type
            });
            insVer.mittBus.on('VER', ({ data }) => {
              this.doQuery({ type: 'VER', data: data })
            })
          }
        } else if (type === 'HOR') {
          let insHor = MeasureDuanmianHor.getIns();
          if (!insHor) {
            mittBus = mitt();
            insHor = MeasureDuanmianHor.create({
              map: MAIN_STORE.GLOBAL_MAP_INS,
              mittBus: mittBus,
            });
            insHor.handleClickCalcDistance();
            insHor.mittBus.on('line', ({ geometry }) => {
              const g_ = geometry.map(v => {
                return [v[0], v[1], 0]
              });
              this.doQuery({ type: 'HOR', data: [g_] })
            })
          }
        }

      }
    },
    // 数据查询
    async doQuery({ type, data }) {
      // if (!this.bufferForm.polygon) { return }
      let url = '';
      let bufferForm = null;
      if (type === 'VER') {
        url = 'iobject/pipe_analyse/section-vertical-list';
        bufferForm = data.map(v => {
          return {
            "BH": v.bh || v.BH,
            "GXXZ": v.gxxz || v.GXXZ,
          }
        });
      } else if (type === 'HOR') {
        url = 'iobject/pipe_analyse/section-cross';
        bufferForm = {
          "drawPoints":
          {
            "datasetNames": [],
            "getFeatureMode": "SPATIAL",
            "spatialQueryMode": "INTERSECT",
            "geometry": { "points": null, "type": null },
            "coordinates": data,
            "type": "MultiLineString"
          }
        }
      }
      if (!url) { return }
      this.selectedId = null;
      this.dataForPaintVER = []
      this.dataForPaintHOR = []
      this.emptyText = '正在分析...'
      const res = await Api.getAnaliseNormal({
        url: url,
        data: bufferForm
      })
      if (type === 'VER') {
        if (res.succ || res.success) {
          this.imageSrc = `/iobject${res.data}/?ts=${new Date().getTime()}`
        } else {
          ElMessage({
            message: res.msg || res.message,
            type: 'warning',
          })
          this.imageSrc = '';
        }
      }
      if (type === 'HOR') {
        if (res.succ || res.success) {
          this.imageSrc = `/iobject${res.data}/?ts=${new Date().getTime()}`
        } else {
          ElMessage({
            message: res.msg || res.message,
            type: 'warning',
          })
          this.imageSrc = '';
        }
      }
      this.emptyText = '暂无数据'
    },
    close() {
      this.isPainting = false;
      this.$emit('close')
    },
    getDetail(data, scope) {
      const ins = MeasureDuanmianVer.getIns();
      if (!ins) { return }
      this.listData = getListData(data)
      this.dialogDrawer = true;
      this.getPos(data, scope, this.listData)
    },
    // 定位
    getPos(data, scope, listData) {
      this.selectedId = scope.$index;
      const coordinates = [data.pointion.x, data.pointion.y];
      this.$store.commit("LOCATION_CERTAIN_VIEW", {
        position: coordinates,
        accu: true
      });
      const ins = MeasureDuanmianVer.getIns();
      if (!ins) { return }
    },
    getPosHOR(data, scope) {
      this.getPos({
        pointion: JSON.parse(JSON.stringify(data))
      }, scope, [])
    },
    closeDrawer() {
      this.dialogDrawer = false;
    },
    normalize(value) {
      if (!value) return ''
      return (Number(value)).toFixed(2)
    }
  },
};
</script>

<template>
  <div class="search-buffer">
    <div class="header">
      <span>
        {{ mainTitle }}
        <small>
          {{ mainTitle_ }}
        </small>
      </span>
      <div class="function-area">
        <div class="icon-area hover-pointer" @click="close">
          <CloseBold></CloseBold>
        </div>
      </div>

    </div>
    <el-form size="small" inline :model="realForm" label-width="40px">
      <el-form-item>
        <el-button v-if="isPainting" text size="small" type="primary" @click="selectPoint">
          取消
        </el-button>
        <el-button v-if="!isPainting" text size="small" type="primary" @click="selectPoint('VER')">
          <el-icon>
            <Sort />
          </el-icon>纵断面分析
        </el-button>
        <el-button v-if="!isPainting" text size="small" type="primary" @click="selectPoint('HOR')">
          <el-icon>
            <Switch />
          </el-icon>横断面分析
        </el-button>
      </el-form-item>
    </el-form>
    <div v-if="imageSrc">
      <el-image style="width: 270px;" :src="imageSrc" :zoom-rate="1.2" :max-scale="7" :min-scale="0.2"
        :preview-src-list="[imageSrc]" show-progress lazy fit="cover" />
    </div>
  </div>
</template>
<style></style>
<style lang="less" scoped>
:deep(.demo-drawer .el-drawer__body) {
  --el-drawer-padding-primary: 0;
}

:deep(.demo-drawer .el-drawer__header) {
  margin-bottom: 20px;
}

.search-buffer {
  &>.header {
    font-size: 16px;
    color: #2168b2;
    margin-bottom: 10px;
    display: flex;
    justify-content: space-between;
    align-items: center;

    &>.function-area {
      display: inline-flex;

      &>.icon-area {
        width: 20px;
        height: 20px;
      }
    }
  }
}
</style>
